package com.yds.developtools.utils

import android.text.TextUtils
import com.google.gson.Gson
import org.xutils.common.Callback
import org.xutils.common.util.KeyValue
import org.xutils.http.RequestParams
import org.xutils.http.body.MultipartBody
import org.xutils.x
import java.io.File
import java.util.*

/**
 * 作者:     YDS
 * 创建时间: 2023/5/29 16:12
 * 页面描述: Xutils文件上传帮助类
 */
@Suppress("unused")
object YDSXutilsUploadFileHelper : YDSBaseHelper() {
    private var cancelable: Callback.Cancelable? = null
    private val mCallbackMap: MutableMap<String, Callback.Cancelable?> = HashMap<String, Callback.Cancelable?>()

    /**
     * 上传文件
     *
     * @param fileUrl   网络地址
     * @param filePaths 本地地址
     * @param obj       其它参数
     * @param callBack  请求回调
     */
    fun uploadFile(
        fileUrl: String, filePaths: List<String>, obj: Any?, callBack: CommonFileCallBack<String?>
    ) {
        val list: MutableList<KeyValue> = ArrayList<KeyValue>()

        // 构建RequestParams对象，传入请求的服务器地址URL
        val params = RequestParams(fileUrl)
        params.connectTimeout = 300 * 1000
        params.readTimeout = 300 * 1000
        params.isAsJsonContent = true

        // 其它参数
        if (null != obj) {
            val json: String = Gson().toJson(obj)
            if (!TextUtils.isEmpty(json)) {
                list.add(KeyValue("parameters", json))
            }
        }

        // 本地文件地址列表
        if (filePaths.isNotEmpty()) {
            for (filePath in filePaths) {
                list.add(KeyValue("file", File(filePath)))
            }
        }
        val body = MultipartBody(list, "UTF-8")
        params.requestBody = body
        cancelable = x.http().post(params, object : Callback.ProgressCallback<String> {
            override fun onWaiting() {
                callBack.onWaiting()
            }

            override fun onStarted() {
                callBack.onStarted()
            }

            override fun onLoading(total: Long, current: Long, isDownloading: Boolean) {
                callBack.onLoading((current * 100 / total).toInt())
            }

            override fun onSuccess(result: String) {
                callBack.onSuccess(result)
            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
                callBack.onError(ex.message)
            }

            override fun onCancelled(cex: Callback.CancelledException?) {
                callBack.onCancelled()
            }

            override fun onFinished() {
                callBack.onFinished()
            }
        })
        mCallbackMap[fileUrl] = cancelable
    }

    /**
     * 上传文件
     *
     * @param fileUrl   网络地址
     * @param filePaths 本地地址
     * @param mapParams    其它参数
     * @param asJson    参数json格式
     * @param callBack  请求回调
     */
    fun uploadFile(fileUrl: String, filePaths: List<String>, mapParams: Map<String, String>?, asJson: Boolean = false, callBack: CommonFileCallBack<String?>) {
        val list: MutableList<KeyValue> = ArrayList<KeyValue>()

        // 构建RequestParams对象，传入请求的服务器地址URL
        val params = RequestParams(fileUrl)
        params.connectTimeout = 300 * 1000
        params.readTimeout = 300 * 1000
        params.isAsJsonContent = asJson

        // 其它参数
        mapParams?.let {
            val iterator = mapParams.iterator()
            while (iterator.hasNext()) {
                params.addParameter(iterator.next().key, iterator.next().value)
            }
        }

        // 本地文件地址列表
        if (filePaths.isNotEmpty()) {
            for (filePath in filePaths) {
                list.add(KeyValue("file", File(filePath)))
            }
        }
        val body = MultipartBody(list, "UTF-8")
        params.requestBody = body
        cancelable = x.http().post(params, object : Callback.ProgressCallback<String> {
            override fun onWaiting() {
                callBack.onWaiting()
            }

            override fun onStarted() {
                callBack.onStarted()
            }

            override fun onLoading(total: Long, current: Long, isDownloading: Boolean) {
                callBack.onLoading((current * 100 / total).toInt())
            }

            override fun onSuccess(result: String) {
                callBack.onSuccess(result)
            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
                callBack.onError(ex.message)
            }

            override fun onCancelled(cex: Callback.CancelledException?) {
                callBack.onCancelled()
            }

            override fun onFinished() {
                callBack.onFinished()
            }
        })
        mCallbackMap[fileUrl] = cancelable
    }

    /*** 作者: YDS 时间: 2023/5/29 16:30 描述: 请求回调 ***/
    interface CommonFileCallBack<T> {
        fun onWaiting() {}
        fun onStarted() {}
        fun onSuccess(result: T)
        fun onLoading(progress: Int) {}
        fun onError(errorMsg: T) {}
        fun onCancelled() {}
        fun onFinished() {}
    }

    /*** 作者: YDS 时间: 2023/5/29 16:30 描述: 查询Callback.Cancelable ***/
    fun queryRequestCancelable(): Map<String, Callback.Cancelable?> {
        return mCallbackMap
    }

    /*** 作者: YDS 时间: 2023/5/29 16:30 描述: 取消请求-通过url ***/
    fun requestCancelByUrl(url: String) {
        val cancelable: Callback.Cancelable? = mCallbackMap[url]
        cancelable?.cancel()
    }

    /*** 作者: YDS 时间: 2023/5/29 16:30 描述: 取消请求-全部 ***/
    fun requestCancel() {
        if (mCallbackMap.isEmpty()) return
        val iterator: Iterator<Map.Entry<String, Callback.Cancelable?>> = mCallbackMap.entries.iterator()
        while (iterator.hasNext()) {
            val entry: Map.Entry<String, Callback.Cancelable?> = iterator.next()
            val cancelable: Callback.Cancelable? = entry.value
            cancelable?.cancel()
        }
    }
}